﻿using NetCoreAPI.Socket;
using Senparc.WebSocket;
using Senparc.Weixin;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.WxOpen.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Commons;
using Entity.Project;
using Authorization;
using Bussiness;
using Entity;
using Bussiness.Mangement.Project;
using Commons.Cache;
using Bussiness.Mangement;
using NetCoreAPI.SSWDSocket;

namespace NetCoreAPI
{
    /// <summary>
    /// .NET Core 自定义 微信小程序 WebSocket 消息处理类
    /// </summary>
    public class WXOpenSocketMessageHandler : WebSocketMessageHandler
    {
        public override Task OnConnecting(WebSocketHelper webSocketHandler)
        {
            //TODO:处理连接时的逻辑
            return base.OnConnecting(webSocketHandler);
        }

        public override async Task OnDisConnected(WebSocketHelper webSocketHandler)
        {
            //TODO:处理断开连接时的逻辑
            //移出房间
            //for (int i = 0; i < SocketHelp.Rooms.Count; i++)
            //{
            //    if (SocketHelp.Rooms[i].Users.Exists(x => x.ConnectionId == webSocketHandler.WebSocket.Context.ConnectionId))
            //    {
            //        int index = SocketHelp.Rooms[i].Users.FindIndex(x => x.ConnectionId == webSocketHandler.WebSocket.Context.ConnectionId);
            //        //SocketHelp.Rooms[i].Users.RemoveAt(index);
            //        SocketHelp.Rooms[i].Users[index].IsConnection = false;//标识断线
            //        await webSocketHandler.WebSocket.Groups.RemoveFromGroupAsync(webSocketHandler.WebSocket.Context.ConnectionId, SocketHelp.Rooms[i].RoomKey);
            //        try
            //        {
            //            IsCurrentUser(i, index, webSocketHandler);
            //        }
            //        catch (Exception ex)
            //        {
            //            var log = new LogHelper<YvanHub>();
            //            log.Error(ex.Message);
            //        }
            //    }
            //}
            await base.OnDisConnected(webSocketHandler);
            return;
        }

        ///// <summary>
        ///// 判断掉线的人在当前房间是否正在操作中
        ///// 正在操作者默认弃牌
        ///// </summary>
        ///// <param name="roomIndex"></param>
        ///// <param name="userIndex"></param>
        ///// <param name="webSocketHandler"></param>
        //private void IsCurrentUser(int roomIndex, int userIndex, WebSocketHelper webSocketHandler)
        //{
        //    var room = SocketHelp.Rooms[roomIndex];
        //    var user = room.Users[userIndex];
        //    if (room.IsStarting == true && room.CurrentUserId == user.UserId)
        //    {
        //        ResultData resultData = new ResultData() { Operation = UserOperation.Result, UserToken = user.UserToken };
        //        SocketHelp.Rooms[roomIndex].Users[userIndex].IsFold = true;
        //        RoomHelper.Next(roomIndex, user.UserToken);
        //        resultData.IsSuccess = true;
        //        resultData.Message = "OK";
        //        resultData.Room = SocketHelp.Rooms[roomIndex];
        //        webSocketHandler.SendMessage(resultData.ToJsonString(), webSocketHandler.WebSocket.Clients.Group(room.RoomKey));
        //    }
        //}

        public override async Task OnMessageReceiced(WebSocketHelper webSocketHandler, ReceivedMessage receivedMessage, string originalData)
        {
            if (receivedMessage == null || string.IsNullOrEmpty(receivedMessage.Message) || string.IsNullOrWhiteSpace(receivedMessage.FormId) || string.IsNullOrWhiteSpace(receivedMessage.SessionId))
            {
                return;
            }
            string userToken = receivedMessage.SessionId;
            string roomKey = receivedMessage.FormId;
            ReceivedMessageData data;
            ResultData resultData= new ResultData() { UserToken=userToken };
            try
            {
                data = receivedMessage.Message.JsonToModel<ReceivedMessageData>();
                data.DateTime = DateTime.Now;
                resultData.ReceivedData = data;
            }
            catch (Exception ex)
            {
                resultData.Message = "未识别消息。Error：" + ex.Message;
                await webSocketHandler.SendMessage(resultData.ToJsonString(), webSocketHandler.WebSocket.Clients.Caller);
                return;
            }
            Current.UserToken = userToken;
            User user;
            #region 只要有UserToken就记录当前访问用户，失败不影响
            try
            {
                int? userId;
                string err;
                Current.VisitToKey = data.VisitTokenTo;
                if (TokenHelp.VerifyUserToken(Current.UserToken, out userId, out err))
                {
                    //记录当前用户Id
                    Current.UserId = userId;
                    //未获取到当前用户
                    if (Current.UserId.HasValue && userId.HasValue && userId.Value>0 && Current.UId > 0)
                    {
                        user = ServiceHelp.GetUserService.GetById(Current.UId);
                        Current.UserJson = user.ToJsonString();
                        var task1 = TokenHelp.ExtensionTimeToHoursAsync(Current.UserId.Value, userToken);
                    }
                    else
                    {
                        resultData.Code = 11;
                        throw new Exception("未查询到用户信息。");
                    }
                }
                else
                {
                    resultData.Code = 11;
                    throw new Exception(err);
                }
            }
            catch(Exception ex) 
            {
                resultData.Message = ex.Message;
                await webSocketHandler.SendMessage(resultData.ToJsonString(), webSocketHandler.WebSocket.Clients.Caller);
                return;
            }
            #endregion

            string errorMsg = string.Empty,jsonData=string.Empty;
            try
            {
                //不同的游戏进入不同的
                switch (data.gameType)
                {
                    case GameType.SSWD:
                        {
                            ReceiveData receiveData = null;
                            var roomData = string.Empty;
                            try
                            {
                                receiveData = data.Message.JsonToModel<ReceiveData>();
                            }
                            catch (Exception)
                            {
                                errorMsg = "系统错误！JSONTOMODELERR.";
                                break;
                            }
                            switch (receiveData.Operation)
                            {
                                case SSWDOperation.None:
                                    break;
                                case SSWDOperation.Create:
                                    {
                                        var room = SSWDSocketHelp.CreateRoom(receiveData, user, roomKey, webSocketHandler.WebSocket.Context.ConnectionId, out errorMsg);
                                        if (string.IsNullOrWhiteSpace(errorMsg))
                                        {
                                           await webSocketHandler.WebSocket.Groups.AddToGroupAsync(webSocketHandler.WebSocket.Context.ConnectionId, room.RoomKey);
                                        }
                                        roomKey = room.RoomKey;
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Join:
                                    {
                                        var room = SSWDSocketHelp.Join(receiveData, user, roomKey, webSocketHandler.WebSocket.Context.ConnectionId, out errorMsg);
                                        if (string.IsNullOrWhiteSpace(errorMsg))
                                        {
                                            await webSocketHandler.WebSocket.Groups.AddToGroupAsync(webSocketHandler.WebSocket.Context.ConnectionId, roomKey);
                                        }
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Ready:
                                    {
                                        var room = SSWDSocketHelp.Ready(receiveData, user, roomKey, out errorMsg);
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Start:
                                    {
                                        var room = SSWDSocketHelp.Start(receiveData, user, roomKey, out errorMsg);
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Talk:
                                    {
                                        var room = SSWDSocketHelp.Talk(receiveData, user, roomKey, out errorMsg);
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Msg:
                                    {
                                        var room = SSWDSocketHelp.Msg(receiveData, user, roomKey, out errorMsg);
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Vote:
                                case SSWDOperation.AbstainVote:
                                    {
                                        var room = SSWDSocketHelp.Vote(receiveData, user, roomKey, out errorMsg);
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                case SSWDOperation.Quit:
                                    {
                                        var room = SSWDSocketHelp.Quit(receiveData, user, roomKey, out errorMsg);
                                        if (string.IsNullOrWhiteSpace(errorMsg))
                                        {
                                            await webSocketHandler.WebSocket.Groups.RemoveFromGroupAsync(webSocketHandler.WebSocket.Context.ConnectionId, roomKey);
                                        }
                                        jsonData = room.ToJsonString();
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    default:
                        jsonData = ""; errorMsg = string.Empty;
                        break;
                }
            }
            catch (Exception ex)
            {
                errorMsg = errorMsg + "---Exception：" + ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(errorMsg))
            {
                resultData.Message = errorMsg;
                resultData.IsSuccess = false;
                await webSocketHandler.SendMessage(resultData.ToJsonString(), webSocketHandler.WebSocket.Clients.Caller);
                return;
            }
            resultData.JsonData = jsonData;
            resultData.IsSuccess = true;
            resultData.Message = "OK";
            await webSocketHandler.SendMessage(resultData.ToJsonString(), webSocketHandler.WebSocket.Clients.Group(roomKey));

            
            
            //await webSocketHandler.SendMessage("正在处理中（反转文字）...", webSocketHandler.WebSocket.Clients.Caller);



        }

       

    }
}
